#!/usr/bin/env bash

REL_SCRIPT_DIR="`dirname \"$0\"`"
SCRIPT_DIR="`( cd \"$REL_SCRIPT_DIR\" && pwd )`"
PROJECT_ROOT="`( cd \"$SCRIPT_DIR/..\" && pwd )`"
JEP_DIR="$PROJECT_ROOT/jep"
JEP_INDEX="$JEP_DIR/README.adoc"

cat > $JEP_INDEX <<EOF
= Index of Jenkins Enhancement Proposals

[%header, cols="^1,<.^4,^1,^1"]
|===
.^| Status
.^| Title
.^| Sponsor(s)
.^| BDFL Delegate

EOF

for f in $(ls $JEP_DIR | sort -n); do
    JEP_README=$JEP_DIR/$f/README.adoc
    if [ -f "$JEP_README" ]; then
        echo "> Processing JEP-$f";
        description=$(head -n 1 $JEP_README | sed 's/^=\ //')
        # grep -A doesn't work on osx grep, use sed instead
        #jep_status=$(grep -x -m 1 -A 1 -e "| Status" $JEP_README | tail -n 1)
        jep_status=$(sed -n '/| Status/,/|/p' $JEP_README | head -n 2 | tail -n 1 | sed 's/| \(.*\) :\(.*\):/| :\2:{nbsp}\1/')

        if [ $? -ne 0 ]; then
            jep_status="Unknown"
        fi;

        sponsor=$(sed -n '/| Sponsor/,/|/p' $JEP_README | head -n 2 | tail -n 1 | sed 's/\([a-zA-Z.]\) /\1{nbsp}/g')
        #sed 's/\(\[[^\]]+\) \([^\]]+\]\)/\1{nbsp\}\2/')


        bdfl=$(sed -n '/| BDFL-Delegate/,/|/p' $JEP_README | head -n 2 | tail -n 1 | sed 's/\([a-zA-Z.]\) /\1{nbsp}/g' | grep -ve "^//" )
        if [ $? -ne 0 ]; then
            bdfl="| _not{nbsp}delegated_"
        fi;

        cat >> $JEP_INDEX <<EOF
$jep_status
| link:${f}/README.adoc[$description]
$sponsor
$bdfl

EOF

    fi;
done;

echo "|===" >> $JEP_INDEX
